<template>
  <div class="search-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </div>
        <div class="header-title">科室搜索</div>
        <div class="close-btn" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"/>
            <line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </div>
      </div>
    </div>
    <!-- 搜索输入框 -->
    <div class="search-input-wrap">
      <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#1877F2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="11" cy="11" r="8"/>
        <path d="m21 21-4.35-4.35"/>
      </svg>
      <input 
        v-model="searchKeyword" 
        @input="handleSearch"
        @keyup.enter="performSearch"
        class="search-input" 
        type="text" 
        placeholder="输入关键字" 
      />
      <button 
        v-if="searchKeyword" 
        @click="clearSearch"
        class="clear-btn"
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#666" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <line x1="18" y1="6" x2="6" y2="18"/>
          <line x1="6" y1="6" x2="18" y2="18"/>
        </svg>
      </button>
    </div>
    <div class="divider"></div>
    
    <!-- 搜索结果 -->
    <div class="search-results">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在搜索...</div>
      </div>
      
      <!-- 搜索结果 -->
      <div v-else-if="searchResults.length > 0" class="results-list">
        <div 
          class="department-card" 
          :class="{ 'selected': selectedDepartmentId === dept._id }"
          v-for="dept in searchResults" 
          :key="dept._id"
          @click="selectDepartment(dept)"
        >
          <DepartmentIcon 
            :department-name="dept.name" 
            :icon-url="dept.icon"
          />
          <div class="dept-info">
            <div class="dept-name">{{ dept.name }}</div>
            <div class="hospital-count">{{ dept.hospitalCount }} 医院</div>
            <div class="price-range">¥{{ dept.priceRange }}</div>
            <div class="next-time">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#666" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"/>
                <polyline points="12,6 12,12 16,14"/>
              </svg>
              <span class="time-label">下一个可用时间</span>
              <span class="time-value">{{ dept.nextTime }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 无结果 -->
      <div v-else-if="hasSearched && searchResults.length === 0" class="no-results">
        <div class="no-results-icon">🔍</div>
        <div class="no-results-text">未找到相关科室</div>
      </div>
    </div>
    
    <!-- 底部按钮 -->
    <div v-if="selectedDepartmentId" class="bottom-button">
      <button 
        class="next-btn" 
        :class="{ 'disabled': !selectedDepartmentId }"
        @click="goToNextStep"
      >
        下一步
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import DepartmentIcon from '../../components/DepartmentIcon.vue'

const router = useRouter()

const searchKeyword = ref('')
const searchResults = ref<any[]>([])
const loading = ref(false)
const hasSearched = ref(false)
const selectedDepartmentId = ref<string>('')

// 从本地存储恢复选中状态
const savedDepartmentId = localStorage.getItem('selectedDepartmentId')
if (savedDepartmentId) {
  selectedDepartmentId.value = savedDepartmentId
}

// 处理搜索输入
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    performSearch()
  } else {
    searchResults.value = []
    hasSearched.value = false
  }
}

// 执行搜索
const performSearch = async () => {
  if (!searchKeyword.value.trim()) return
  
  loading.value = true
  hasSearched.value = true
  
  try {
    // 直接使用axios发送搜索请求
    const response = await axios.get('http://localhost:3000/sow/departments/search', {
      params: {
        keyword: searchKeyword.value
      }
    })
    console.log('搜索API响应:', response.data)
    // 根据后端返回的数据结构，数据在 response.data.data 中
    searchResults.value = response.data.data || []
    console.log('处理后的搜索结果:', searchResults.value)
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
  } finally {
    loading.value = false
  }
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  searchResults.value = []
  hasSearched.value = false
}

// 选择科室
const selectDepartment = (dept: any) => {
  console.log('选择科室:', dept.name)
  
  // 更新选中状态
  selectedDepartmentId.value = dept._id
  
  // 存储选中的科室ID到本地存储
  localStorage.setItem('selectedDepartmentId', dept._id)
  
  // 存储选中的科室完整信息到本地存储
  localStorage.setItem('selectedDepartment', JSON.stringify(dept))
  
  // 不立即跳转，让用户看到选中效果
  // 用户需要点击"下一步"按钮才会跳转
}

// 跳转到下一步
const goToNextStep = () => {
  console.log('点击下一步')
  // 检查是否有选中的科室
  if (selectedDepartmentId.value) {
    router.push('/hospital-select')
  } else {
    // 使用轻提示
    showToast('请先选择一个科室')
  }
}

// 轻提示函数
const showToast = (message: string) => {
  // 创建toast元素
  const toast = document.createElement('div')
  toast.className = 'toast-message'
  toast.textContent = message
  
  // 添加到页面
  document.body.appendChild(toast)
  
  // 显示动画
  setTimeout(() => {
    toast.classList.add('show')
  }, 10)
  
  // 3秒后移除
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => {
      document.body.removeChild(toast)
    }, 300)
  }, 3000)
}


</script>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background: #f6f8fc;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

.header {
  background: #1877F2;
  padding: 12px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 44px;
}

.back-btn, .close-btn {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.search-input-wrap {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  margin: 24px 20px 0 20px;
  padding: 0 12px;
  height: 44px;
  box-shadow: 0 2px 8px rgba(24,119,242,0.04);
  position: relative;
}
.search-icon {
  margin-right: 8px;
  flex-shrink: 0;
}
.search-input {
  border: none;
  outline: none;
  font-size: 16px;
  color: #222;
  background: transparent;
  flex: 1;
  &::placeholder {
    color: #bbb;
    font-size: 16px;
  }
}
.clear-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  margin-left: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.divider {
  height: 1px;
  background: #eaeaea;
  margin: 18px 20px 0 20px;
}

.search-results {
  padding: 16px;
  padding-bottom: 100px; // 为底部按钮留出空间
}

.loading-container, .no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #666;
  font-size: 16px;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1877F2;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  margin-bottom: 10px;
}

.no-results-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.no-results-text {
  margin-bottom: 15px;
  text-align: center;
}

.results-list {
  .department-card {
    background: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(24,119,242,0.15);
    }
    
    &.selected {
      border-color: #1877F2;
      background: linear-gradient(135deg, #f8fbff 0%, #e3f2fd 100%);
      box-shadow: 0 4px 16px rgba(24,119,242,0.2);
      transform: translateY(-2px);
      
      .dept-name {
        color: #1877F2;
        font-weight: 700;
      }
      
      .price-range {
        color: #1877F2;
        font-weight: 600;
      }
      
      .time-value {
        color: #1877F2;
        font-weight: 600;
      }
    }
  }



  .dept-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .dept-name {
    font-size: 16px;
    font-weight: 600;
    color: #222;
  }

  .hospital-count {
    font-size: 14px;
    color: #666;
  }

  .price-range {
    font-size: 14px;
    color: #ff6b35;
    font-weight: 500;
  }

  .next-time {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #666;
    
    .time-label {
      flex: 1;
    }
    
    .time-value {
      color: #1877F2;
      font-weight: 500;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 轻提示样式
.toast-message {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0.8);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 9999;
  opacity: 0;
  transition: all 0.3s ease;
  pointer-events: none;
  
  &.show {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.next-btn {
  width: 100%;
  height: 48px;
  background: #1877F2;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background: #1565c0;
  }
  
  &:active {
    background: #0d47a1;
  }
  
  &.disabled {
    background: #ccc;
    color: #999;
    cursor: not-allowed;
    
    &:hover {
      background: #ccc;
    }
  }
}
</style>
      
    
    


              